package drive.Service.ServiceFormat;

import com.google.gson.Gson;
import drive.Mapper.UserMapper;
import drive.Model.User;
import drive.Service.ServiceInterface.LoginService;
import drive.pojo.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceA implements LoginService {
    @Autowired
    private UserMapper userMapper;

    Gson gson = new Gson();
    // 创建用户
    @Override

    public String createUser(User user) {
        User find = userMapper.selectUserByUsername(user.getUsername());
        if(find==null){
            User emailCheck = userMapper.selectUserByEmail(user.getEmail());
            if(emailCheck==null){
                userMapper.insertUser(user);
                return "User created successfully with ID: " + user.getUserID();
            }
            return "email is already registered";
        }
        return "Username is already created";
    }

    // 根据ID获取用户
    @Override
    public User getUserById(int userID) {
        return userMapper.selectUserById(userID);
    }

    // 获取所有用户
    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAllUsers();
    }

    // 更新用户
    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    // 删除用户
    @Override
    public int deleteUser(int userID) {
        return userMapper.deleteUser(userID);
    }

    // 根据用户名获取用户
    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }

    // 根据邮箱获取用户
    @Override
    public User getUserByEmail(String email) {
        return userMapper.selectUserByEmail(email);
    }

    // 用户登录
    @Override
    public String login(String username, String password) {
        Map<String,Object> map = new HashMap<>();
        User user = userMapper.selectUserByUsernameAndPassword(username, password);
        map.put("user",user);
        String token = JwtUtils.GenJwt(user.getUserID(),"user");
        map.put("token",token);
        return gson.toJson(map);
    }
}
